<template>
  <div>

    <section class="flex w-full justify-between">
      <div class="flex">
        <el-button class="mb-2" size="small" type="primary" plain @click="handleOpenDialog(null)">新增</el-button>
        <el-button type="success" @click="dialogVisibleAlter = true">一键修改</el-button>
        <el-button type="danger" @click="deBounceWrap(handleDeleteAll)">批量删除</el-button>
        <el-button type="warning" @click="deBounceWrap(handleCrit)">暴击奖池</el-button>
      </div>
      <el-button round type="danger" @click="$emit('updateVisible')">返回</el-button>
    </section>

    <el-table
      :data="dataList" border style="width: 100%"
      @selection-change="handleSelectionChange1"
    >
      <el-table-column type="selection" width="55"> </el-table-column>
      <el-table-column prop="gift_name" label="名称" width="180">
      </el-table-column>
      <el-table-column prop="price" label="价格" width="180">
      </el-table-column>
      <el-table-column prop="picture" label="图片">
        <template slot-scope="{ row: { picture } }">
          <el-popover placement="right" width="220" trigger="hover">
            <el-image :src="picture" alt="" style="max-width: 200px;" />
            <el-image
              slot="reference"
              :src="picture"
              alt=""
              style="width: 100px; "
            />
          </el-popover>
        </template>
      </el-table-column>
      <el-table-column prop="number" label="数量"> </el-table-column>
      <el-table-column prop="critical_times" label="暴击数量"></el-table-column>
      <el-table-column prop="quality" label="品质"> </el-table-column>
      <el-table-column prop="address" label="操作" width="300">
        <template slot-scope="{ row }">
          <el-button
            size="mini"
            @click="handleOpenDialog(row)"
            plain
            type="primary"
          >编辑</el-button>
          <el-button
            type="danger"
            icon="el-icon-delete"
            size="mini"
            plain
            @click="deBounceWrap(handleClickDelete, row)"
          >删除</el-button>
          <el-button v-if="critical_gift_ids.includes(row.gift_id)" @click="openDeploy(row)" plain>配置暴击数量</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-dialog @close="visible = false" title="编辑" :visible.sync="visible">
      <span class="mr-4">暴击数量: </span>
      <el-input-number :min="0" type="number" v-model="critical_times"></el-input-number>
      <div slot="footer">
        <el-button @click="visible = false" plain>取消</el-button>
        <el-button @click="deploy" plain>提交</el-button>
      </div>
    </el-dialog>

    <!--  一键修改  -->
    <el-dialog
      title="一键修改"
      :visible.sync="dialogVisibleAlter"
      @close="handleClearForm"
      width="60%"
    >
      <div
        class="flex items-center mb-3"
        v-for="item in dataList"
        :key="item.id"
      >
        <p class="w-20 font-bold">{{ item.gift_name }}</p>
        <el-input-number :min="0" v-model="item.number"></el-input-number>
      </div>

      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="handleSubmitFormAllAlter">提交</el-button>
      </span>
    </el-dialog>

    <!--  新增 or 编辑  -->
    <el-dialog
      :title="dialogTitle"
      :visible.sync="dialogVisible"
      @close="handleClearForm"
      width="30%"
    >
      <div class="flex items-center mb-8">
        <div class="w-20 mr-4">选择礼物</div>
        <el-select v-model="form.giftId" filterable placeholder="请选择">
          <el-option
            v-for="item in options"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          >
          </el-option>
        </el-select>
      </div>

      <div class="flex items-center mb-8">
        <div class="w-20 mr-4">数量</div>
        <el-input-number :min="0" v-model="form.number"></el-input-number>
      </div>

      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleSubmitForm">提交</el-button>
      </span>
    </el-dialog>

  </div>
</template>

<script>
import {getUserPool, setNumCritical} from "@/api/luckyTreeGame/luckyTreeGame";
import {addPool, getAllGiftList, delPoolGift, editPoolGift} from "@/api/luckyTreeGame/specialPrizePoolManagement";

const STATUS = {
  edit: "编辑",
  addNew: "新增"
};

export default {
  name: "userDetails",
  props: {
    userId: {
      type: Number
    }
  },
  data() {
    return {
      dataList: [],
      critical_gift_ids: [],
      critical_times: 0,
      criticalRow: {},
      visible: false,
      /* 新增编辑dialog开关 */
      dialogVisible: false,
      multipleSelection: [],
      /* 一键修改dialog开关 */
      dialogVisibleAlter: false,
      /* dialog title */
      dialogTitle: "",
      /* 下拉列表 */
      options: [],
      /* 表单数据 */
      form: {
        /* 当前编辑行的id */
        id: -1,
        giftId: undefined,
        number: 0
      },
    }
  },
  created() {
    this.getUserList(this.userId)
    /* 获取下拉列表数据 */
    this.getAllGiftList();
  },
  methods: {
    handleCrit() {
      this.$router.push({
        name: 'criticalPrizePoolUserList',
        query: {
          pool_type: 40,
          user_id: this.userId
        }
      })
    },
    handleSelectionChange1(val) {
      this.multipleSelection = val;
    },
    //批量删除
    handleDeleteAll() {
      if (this.multipleSelection.length) {
        /* 存在勾选数据 */ const ids = this.multipleSelection.reduce(
          (pre, currRow) => {
            pre += `${currRow.id},`;
            return pre;
          },
          ""
        );
        delPoolGift({ ids })
          .then(() => this.$message.success("删除成功！"))
          .catch(console.error)
          .finally(() => /* 刷新数据 */ {
            this.multipleSelection = [];
            this.getUserList(this.userId);
          });
      } /* 不存在勾选数据 */ else {
        this.$message.warning("请勾选要删除的数据！");
      }
    },
    //删除
    handleClickDelete(row) {
      this.$confirm("确认删除!?此步骤无法恢复。", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          let data = {
            ids: row.id
          };
          delPoolGift(data).then(async res => {
            if (res.code === 200) {
              await this.getUserList(this.userId);
              this.$message({
                type: "success",
                message: "删除成功"
              });
            }
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除"
          });
        });
    },
    /* 一键修改确认回调 */
    handleSubmitFormAllAlter() {
      let gift_info = this.tableList.reduce((pre, curr) => {
        pre += `${curr.id},${curr.gift_id},${curr.number};`;
        return pre;
      }, "");
      editPoolGift({ user_id: this.userId, gift_info: gift_info})
        .then(() => {
          this.getUserList(this.userId);
        })
        .catch(this.errorMessage);
      this.dialogVisibleAlter = false;
    },
    openDeploy(row) {
      this.criticalRow = row
      this.critical_times = row.critical_times
      this.visible = true
      console.log(this.criticalRow)
    },
    async deploy() {
      const res = await setNumCritical({
        critical_times: this.critical_times, pool_type: 40, gift_id: this.criticalRow.gift_id, pool_type_id: this.criticalRow.type, user_id: this.userId, is_next: 0 })
      if (res.code === 200) {
        this.$message.success(res.message)
        this.visible = false
        await this.getUserList(this.userId)
      }
    },
    /* 获取下拉列表数据 */
    getAllGiftList() {
      getAllGiftList(2)
        .then(({ data }) => {
          this.options = data;
        })
        .catch(this.errorMessage);
    },
    async getUserList(userId) {
      const { data: { list, critical_gift_ids } } = await getUserPool(userId)
      this.critical_gift_ids = critical_gift_ids
      this.dataList = list
    },
    /* dialog 确定时回调 */
    handleSubmitForm() {
      if (this.dialogTitle === STATUS.edit) {
        /* 编辑 */ editPoolGift({
          user_id: this.userId,
          gift_info: `${this.form.id},${this.form.giftId},${this.form.number}`}
        )
          .then(res => {
            this.$message.success("编辑成功~");
            this.getUserList(this.userId);
          })
          .catch(this.errorMessage);
      } else if (this.dialogTitle === STATUS.addNew) {
        /* 新增 */ addPool({ user_id: this.userId, gift_id: this.form.giftId, gift_num: this.form.number })
          .then(res => {
            this.$message.success("新增成功~");
            this.getUserList(this.userId);
          })
          .catch(this.errorMessage);
      }
      this.dialogVisible = false;
    },
    /* dialog 关闭前回调 */
    handleClearForm() {
      this.form = { giftId: undefined, number: 0 };
      this.getUserList(this.userId);
    },
    /* 打开dialog回调 */
    handleOpenDialog(row) {
      if (row) {
        console.log('row', row)
        /* 编辑 */ this.dialogTitle = STATUS.edit;
        this.form.id = row.id;
        this.form.number = row.number;
        this.form.giftId = row.gift_id;
      } /* 新增 */ else {
        this.dialogTitle = STATUS.addNew;
      }
      this.dialogVisible = true;
    },
  }
}
</script>

<style scoped>

</style>
